package com.wanhelibs.indicator;

import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wanhe.base.util.ObjectUtil;
import com.wanhe.shoppingcart.bean.CartItem;
import com.wanhe.shoppingcart.manager.CartManager;
import com.wanhe.shoppingcart.manager.ICartChangeObserver;
import com.wanhe.shoppingcart.manager.ICartItem;
import com.wanhelibs.R;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by Administrator on 2016/5/31.
 */
public class CustomTab extends LinearLayout implements ICartChangeObserver {

    private static final String TAG = CustomTab.class.getSimpleName();

    TextView tvTab;
    TextView tvFoodCount;
    private int mTypeID = -1;

    public CustomTab(Context context) {
        this(context, null);
    }

    public CustomTab(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
        setOrientation(HORIZONTAL);
        init(context, attrs);
        initComponent();
    }

    /**
     * 绑定菜品类型的ID
     *
     * @param id
     * @param name
     */
    public void bindDishType(int id, String name) {
        this.mTypeID = id;
        tvTab.setText(name);
        calculateCount();
        CartManager.getInstance().addCartObserver(this);
    }

    public int getmTypeID() {
        return mTypeID;
    }

    private void initComponent() {
        setBackgroundDrawable(getResources().getDrawable(R.drawable.tab_bg_selector));
        tvFoodCount.setBackgroundDrawable(getResources().getDrawable(R.drawable.chaoniu_food_count_bg_selector));
        setCount(0);
    }

    private void init(Context context, AttributeSet attrs) {
        setGravity(Gravity.CENTER);
        View view = LayoutInflater.from(context).inflate(R.layout.custom_tab_item_layout, this, true);
        tvTab = (TextView) view.findViewById(R.id.tv_tab);
        tvFoodCount = (TextView) view.findViewById(R.id.tv_food_count);
    }

    private void calculateCount() {
        List<ICartItem> totalCartItem = CartManager.getInstance().getTotalCartItem();
        Observable.just(totalCartItem).map(new Function<List<ICartItem>, Integer>() {
            @Override
            public Integer apply(@NonNull List<ICartItem> iCartItems) throws Exception {
                int count = 0;
                if (ObjectUtil.checkObjectList(iCartItems)) {
                    for (ICartItem item : iCartItems) {
                        if (mTypeID == ((CartItem)item).getDish().tid) {
                            count += item.getCount();
                        }
                    }
                }
                return count;
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(@NonNull Integer integer) throws Exception {
                setCount(integer);
            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        CartManager.getInstance().removeObserver(this);
        super.onDetachedFromWindow();
    }

    /**
     * 设置tab文字右上角的数量信息
     *
     * @param count
     */
    private void setCount(final int count) {
        tvFoodCount.post(new Runnable() {
            @Override
            public void run() {
                if (count == 0) {
                    tvFoodCount.setVisibility(GONE);
                } else {
                    tvFoodCount.setVisibility(VISIBLE);
                    tvFoodCount.setText(String.valueOf(count));
                }
            }
        });
    }

    @Override
    public boolean isNeedUpdate() {
        return true;
    }

    @Override
    public void onCartChanged(boolean isAdd) {
        //购物车变化的时候变化顶部的数量
        if (mTypeID == -1) {
            return;
        }
        int typeId = ((CartItem) CartManager.getInstance().getCurrentItem()).getDish().tid;

        if (typeId == mTypeID) {
            calculateCount();
        }
    }
}
